// Copyright 2024 Tvux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package _042

func trap(height []int) int {
	left, right := 0, len(height)-1
	leftMax, rightMax := 0, 0
	res := 0
	for left < right { // 这里不用等于，因为是哪边矮就移动那边，所以当left==right的时候，肯定是最高的那个柱子，是接不了水的
		leftMax = max(leftMax, height[left])    // 当前左边的最大高度
		rightMax = max(rightMax, height[right]) // 当前右边的最大高度
		if leftMax < rightMax {
			// 当前左边的最大高度小于右边的最大高度，那么当前这个位置能接多少水就取决于左边（短板原理）
			res += leftMax - height[left]
			left++ // 向右移动，看能不能更新左边的最大高度
		} else {
			res += rightMax - height[right]
			right--
		}
	}
	return res
}
